<?php
/**
 * Created by PhpStorm.
 * User: geyouwen
 * Date: 16/7/12
 * Time: 下午1:52
 */

namespace Backend\Controller;

use Think\Exception;

class AdminController extends BaseController
{
    private $admin;
    public function __construct()
    {
        parent::__construct();
        $this->admin     = D('admin');
    }

    //管理员列表
    public function index()
    {
        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $order      = 'regdate asc';
        $list =  $this->getpage($this->admin, '', $order, C('page_size')); //$this->admin->order($order)->limit($Page->firstRow.','.$Page->listRows)->select();
        $role = array();
        if($list['list'])
        {
            $role_ids = i_array_column($list['list'], 'role_id');
            $where = array('id' => array('in', $role_ids));
            $role  = D('admin_role')->where($where)->field('id,name')->select();
            if($role) $role = changeArrIndex($role, 'id');
        }
        $big_menu = array(
            'title' => '增加管理员',
            'uri' => U('backend/admin/add'),
        );
        $this->assign('list',$list['list']);// 赋值数据集
        $this->assign('page',$list['page']);// 赋值分页输出
        $this->assign('big_menu', $big_menu);
        $this->assign('role', $role);
        $this->display(); // 输出模板

    }

    //todo add
    public function add()
    {
        if(IS_AJAX)
        {
            $data = array(
                'username' => I('username'),
                'email'    => I('email'),
                'status'   => I('status'),
                'mobile'   => I('mobile'),
                'role_id'  => I('role'),
                'password'  => md5(C('APP_MCRYPT').I('password')),
                'repassword'  => md5(C('APP_MCRYPT').I('repassword')),
                'regdate'  => time(),
                'lastdate' => time(),
                'regip'    => get_client_ip(),
                'lastip'   => get_client_ip(),
            );
            $verify = $this->verifydata($data);
            if($verify)
            {
                $return = array(
                    'status' => 0,
                    'msg'    => $verify
                );
                $this->ajaxReturn($return);
            }
            $check_exist = $this->check_exist($data, $userid = '');
            if($check_exist)
            {
                $return = array(
                    'status' => 0,
                    'msg'    => $check_exist
                );
                $this->ajaxReturn($return);
            }
            try{
                D('admin')->add($data);
                $return = array(
                    'status' => 1,
                    'msg'    => L('operation_success')
                );
            } catch(Exception $e)
            {
                $msg = $e->getMessage();
                $return = array(
                    'status' => 0,
                    'msg'    => $msg
                );

            }
            $this->ajaxReturn($return);
        }
        $role_list = D('admin_role')->allabled();
        $this->assign('role_list', $role_list);
        $this->display();
    }

    //对新增的管理员数据进行验证
    private function verifydata($data, $verify_password= true)
    {
        if(!trim($data['username']))
        {
            return $msg = '请输入管理员名称';
        }
        if($verify_password)
        {
            if(!trim($data['password']))
            {
                return $msg = '请输入密码';
            }
            if(!trim($data['repassword']))
            {
                return $msg = '请输入确认密码';
            }
            if(trim($data['repassword']) != trim($data['password']))
            {
                return $msg = '两次输入的密码不一致';
            }
        }

        if(!trim($data['role_id']))
        {
            return $msg = '请选择角色';
        }
        if(!trim($data['email']))
        {
            return $msg = '请输入邮箱';
        }
        $reg_email  = '/^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/';
        if(!preg_match($reg_email, $data['email']))
        {
            return $msg = '请输入正确的邮箱';
        }

        if(!trim($data['mobile']))
        {
            return $msg = '请输入手机号';
        }
        $reg_mobile = '/^0{0,1}(13[0-9]|15[7-9]|153|156|18[7-9])[0-9]{8}$/';
        if(!preg_match($reg_mobile, $data['mobile']))
        {
            return $msg = '请输入正确的手机号';
        }
        //数据是否有重复

        return false;
    }

    /**
     * 检测重复数据
     * @param $data
     * @param int $userid 当前修改的数据id
     * @return bool|string
     */
    private function check_exist($data, $userid = '')
    {
        $check_name = D('admin')->is_exist('username', $data['username'], $userid);
        if($check_name) return '管理员名称已经被注册';

        $check_email = D('admin')->is_exist('email', $data['email'], $userid);
        if($check_email) return '邮箱已经被注册，请换一个试试';

        $check_mobile = D('admin')->is_exist('mobile', $data['mobile'], $userid);
        if($check_mobile) return '手机号已经被注册，请换一个试试';
        return false;
    }


    //todo edit
    public function edit()
    {
        if(IS_AJAX)
        {
            $verify_password = false;
            $data = array(
                'userid'      => I('uid'),
                'username' => I('username'),
                'email'    => I('email'),
                'status'   => I('status'),
                'mobile'   => I('mobile'),
                'role_id'  => I('role'),
            );
            if(I('password') && I('repassword'))
            {
                $verify_password = true;
                $data['password'] = md5(C('APP_MCRYPT').I('password'));
                $data['repassword'] = md5(C('APP_MCRYPT').I('repassword'));

            }
            $verify = $this->verifydata($data, $verify_password);
            if($verify)
            {
                $return = array(
                    'status' => 0,
                    'msg'    => $verify
                );
                $this->ajaxReturn($return);
            }
            $check_exist = $this->check_exist($data, $data['userid']);
            if($check_exist)
            {
                $return = array(
                    'status' => 0,
                    'msg'    => $check_exist
                );
                $this->ajaxReturn($return);
            }
            try{
                $where = array('userid' => $data['userid']);
                unset($data['userid']);
                D('admin')->where($where)->save($data);
                $return = array(
                    'status' => 1,
                    'msg'    => L('operation_success')
                );
            } catch(Exception $e)
            {
                $msg = $e->getMessage();
                $return = array(
                    'status' => 0,
                    'msg'    => $msg
                );

            }
            $this->ajaxReturn($return);

        }
        $id = I('id');
        $data = $this->admin->find($id);
        if(!$data) $this->error(L('no_source'), U('backend/admin/index'));
        $role_list = D('admin_role')->allabled();
        $this->assign('role_list', $role_list);
        $this->assign('data', $data);
        $this->display();
    }

    //todo del
    public function delete()
    {
       $id = I('id');
       $where = array(
           'userid' => $id,
       );
        if(isset($_POST['params']))
        {
            $params = $_POST['params'];
            $where = array(
                'userid' => array('in', $params)
            );
        }
        $data = array(
            'status' => 0
        );
       try{
           $this->admin->where($where)->save($data);
           $msg = array('status' =>1, 'msg' => L('operation_success'));
       } catch (Exception $e)
       {
           $msg = array('status' =>0, 'msg'=> L('operation_error'));
       }
        $this->ajaxReturn($msg);
    }

    //重新启用帐户
    public function recovery()
    {
        $id = I('id');
        $where = array(
            'userid' => $id,
        );
        $data = array(
            'status' => 1
        );
        try{
            $this->admin->where($where)->save($data);
            $msg = array('status' =>1, 'msg' => L('operation_success'));
        } catch (Exception $e)
        {
            $msg = array('status' =>0, 'msg'=> L('operation_error'));
        }
        $this->ajaxReturn($msg);
    }

}